﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HYSpace
{
	[Transaction(TransactionMode.Manual)]
	public class EstimateHeatCoolLoad : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			if (commandData == null)
			{
				throw new System.ArgumentNullException("commandData", "is null");
			}
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Selection selection = activeUIDocument.Selection;
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(1);
			if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			FormEstimateLoad formEstimateLoad = null;
			Result result;
			try
			{
				formEstimateLoad = new FormEstimateLoad();
				if (formEstimateLoad.ShowDialog() == DialogResult.OK)
				{
					EstimateLoadOperate estimateLoadOperate = new EstimateLoadOperate(activeUIDocument);
					bool flag = formEstimateLoad.BeSelectSpace();
					if (!flag)
					{
						estimateLoadOperate.HeatIndex = formEstimateLoad.GetHeatLoad();
						estimateLoadOperate.CoolIndex = formEstimateLoad.GetCoolLoad();
					}
					List<LoadEstimateParam> list = estimateLoadOperate.SearchElementSet(flag);
					if (list == null || list.Count < 1)
					{
						YJKMessageBox.Show(estimateLoadOperate.SearchMessage);
					}
					else
					{
						new FormEstimateLoadShow(list, activeUIDocument).ShowDialog();
					}
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				formEstimateLoad.Close();
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
                    if ((int)status == 1)
					{
						transaction.Commit();
					}
                    else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
